package ilender.models;

import java.io.Serializable;
import org.apache.ibatis.exceptions.PersistenceException;

import lombok.*;

import ilender.mappers.*;

/**
 * Base class for models.
 */
@Data @NoArgsConstructor
public class BaseModel implements Serializable{
	private long id;

	/**Checks if this model has not been inserted to the database yet.*/
	public boolean isNewRecord(){
		return 0==getId();
	}

	/**
	 * Saves this model to the database, creating a new record if needed.
	 *
	 * Throws an exception upon failure.
	 */
	public void save(BaseMapper mapper){
		if(isNewRecord()){
			setId(mapper.insert(this));
		}else{
			mapper.update(this);
		}
	}

	/**
	 * Saves this model to the database, creating a new record if needed.
	 *
	 * @return null upon success, error message upon failure.
	 */
	public String trySave(BaseMapper mapper){
		try{
			save(mapper);
			return null;
		}catch(PersistenceException e){
			return e.getCause().getMessage();
		}
	}

	/**"Black Hole" property for ignoring fields in MyBatis mapping.*/
	public void setNone(Object none){
	}
}
